package com.wuliu.system.service.impl;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wuliu.common.core.domain.entity.SysDept;
import com.wuliu.common.core.domain.entity.SysMenu;
import com.wuliu.common.core.domain.entity.SysRole;
import com.wuliu.common.core.domain.entity.SysUser;
import com.wuliu.common.exception.ServiceException;
import com.wuliu.common.utils.DateUtils;
import com.wuliu.common.utils.SecurityUtils;
import com.wuliu.common.utils.StringUtils;
import com.wuliu.system.domain.*;
import com.wuliu.system.mapper.*;
import com.wuliu.system.service.IBasOrderRuleService;
import com.wuliu.system.service.ISysConfigService;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wuliu.system.service.ISysAccountService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 帐套Service业务层处理
 *
 * @author ruoyi
 * @date 2023-09-23
 */
@Service
public class SysAccountServiceImpl implements ISysAccountService {
    @Resource
    private SysAccountMapper sysAccountMapper;
    @Resource
    private ISysConfigService configService;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysMenuMapper sysMenuMapper;
    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private BasOrderRuleMapper basOrderRuleMapper;

    /**
     * 查询帐套
     *
     * @param id 帐套主键
     * @return 帐套
     */
    @Override
    public SysAccount selectSysAccountById(String id) {
        return sysAccountMapper.selectSysAccountById(id);
    }

    /**
     * 查询帐套列表
     *
     * @param sysAccount 帐套
     * @return 帐套
     */
    @Override
    public List<SysAccount> selectSysAccountList(SysAccount sysAccount) {
        return sysAccountMapper.selectSysAccountList(sysAccount);
    }

    /**
     * 新增帐套
     *
     * @param sysAccount 帐套
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertSysAccount(SysAccount sysAccount) {
        SysAccount account = sysAccountMapper.selectOne(new LambdaQueryWrapper<SysAccount>()
                .eq(SysAccount::getSysAccount, sysAccount.getSysAccount()));
        if (null != account) {
            throw new ServiceException("账套号已存在");
        }
        sysAccount.setId(IdUtil.randomUUID());
        sysAccount.setCreateTime(DateUtils.getNowDate());
        sysAccount.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        //同步新建用户
        SysUser sysUser = new SysUser();
        sysUser.setSysAccount(sysAccount.getSysAccount());
        sysUser.setUserName(sysAccount.getSysAccount());
        sysUser.setNickName(sysAccount.getAccountName());
        sysUser.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        sysUser.setCreateTime(DateUtils.getNowDate());
        sysUser.setDeptId(0L);
        String password = configService.selectConfigByKey("sys.user.initPassword");
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        sysUserMapper.insertUser(sysUser);
        long userId = sysUser.getUserId();
        //同步新建角色
        SysRole sysRole = new SysRole();
        sysRole.setSysAccount(sysAccount.getSysAccount());
        sysRole.setRoleName("系统管理员");
        sysRole.setDataScope("1");
        sysRole.setStatus("0");
        sysRole.setRoleSort(0);
        sysRole.setRoleKey("system");
        sysRole.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        sysRoleMapper.insertRole(sysRole);
        long roleId = sysRole.getRoleId();
        //新增角色功能菜单
        SysMenu sysMenu = new SysMenu();
        sysMenu.setNewFlag(1);
        List<SysMenu> sysMenus = sysMenuMapper.selectMenuList(sysMenu);
        if (StringUtils.isNotEmpty(sysMenus)) {
            List<SysRoleMenu> insRoleMenu = sysMenus.stream().map(t -> {
                SysRoleMenu roleMenu = new SysRoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(t.getMenuId());
                return roleMenu;
            }).collect(Collectors.toList());
            sysRoleMenuMapper.batchRoleMenu(insRoleMenu);
        }
        //新增用户角色表
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setRoleId(roleId);
        sysUserRole.setUserId(userId);
        sysUserRoleMapper.batchUserRole(Stream.of(sysUserRole).collect(Collectors.toList()));
        //新增sys_dept表架构
        SysDept sysDept = new SysDept();
        sysDept.setParentId(0L);
        sysDept.setAncestors("0");
        sysDept.setDeptName(sysAccount.getAccountName());
        sysDept.setOrderNum(0);
        sysDept.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        sysDept.setCreateTime(DateUtils.getNowDate());
        sysDept.setSysAccount(sysAccount.getSysAccount());
        sysDeptMapper.insertDept(sysDept);
        BasOrderRule orderRule = new BasOrderRule();
        orderRule.setId(IdUtil.randomUUID());
        orderRule.setSysAccount(sysAccount.getSysAccount());
        orderRule.setCreateBy(sysUser.getUserName());
        orderRule.setCreateTime(DateUtils.getNowDate());
        orderRule.setType(1);
        orderRule.setPrefix("6");
        orderRule.setLength(9);
        basOrderRuleMapper.insertBasOrderRule(orderRule);
        return sysAccountMapper.insertSysAccount(sysAccount);
    }

    /**
     * 修改帐套
     *
     * @param sysAccount 帐套
     * @return 结果
     */
    @Override
    public int updateSysAccount(SysAccount sysAccount) {
        sysAccount.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
        sysAccount.setUpdateTime(DateUtils.getNowDate());
        return sysAccountMapper.updateSysAccount(sysAccount);
    }

    /**
     * 批量删除帐套
     *
     * @param ids 需要删除的帐套主键
     * @return 结果
     */
    @Override
    public int deleteSysAccountByIds(String[] ids) {
        String id = ids[0];
        SysAccount account = sysAccountMapper.selectSysAccountById(id);
        //同步删除账套角色和用户
        sysRoleMenuMapper.deleteRoleMenuBySysAccount(account.getSysAccount());
        sysRoleMapper.delete(new LambdaQueryWrapper<SysRole>().eq(SysRole::getSysAccount, account.getSysAccount()));
        sysUserRoleMapper.deleteUserRoleBySysAccount(account.getSysAccount());
        sysUserMapper.delete(new LambdaQueryWrapper<SysUser>().eq(SysUser::getSysAccount, account.getSysAccount()));
        sysDeptMapper.delete(new LambdaQueryWrapper<SysDept>().eq(SysDept::getSysAccount, account.getSysAccount()));
        return sysAccountMapper.deleteSysAccountByIds(ids);
    }

    /**
     * 删除帐套信息
     *
     * @param id 帐套主键
     * @return 结果
     */
    @Override
    public int deleteSysAccountById(String id) {
        return sysAccountMapper.deleteSysAccountById(id);
    }
}
